/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.persistence.memory;

import apus.entity.PhoneNumber;
import apus.entity.RealPerson;
import apus.entity.Subscriber;
import apus.persistence.OrganizationDAO;
import apus.persistence.PersonDAO;
import apus.persistence.PhoneNumberDAO;
import apus.services.ServiceLocator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author  Maxim Vasilevsky
 * @author  Roman Dyatkovsky
 * @since APUS v0.2
 * @see AbstractMemoryDAO
 * @see PhoneNumberDAO
 */
public class MemoryPhoneNumberDAO extends AbstractMemoryDAO<PhoneNumber> implements PhoneNumberDAO{
    
    private static Map<Integer,PhoneNumber> dataSource = new HashMap<>();
    private static Integer counter = 1;
    
    @Override
    public void create(PhoneNumber entity) {
        super.create(entity);
        
        AbstractMemoryDAO DAO;
        
        if (entity.getOwner().getClass().equals(RealPerson.class)){
            DAO = (AbstractMemoryDAO)ServiceLocator.getService(PersonDAO.class);
        } else {
            DAO = (AbstractMemoryDAO)ServiceLocator.getService(OrganizationDAO.class);
        }

        Subscriber subscriber = (Subscriber)DAO.read(entity.getOwner().getId());
        subscriber.addPhoneNumber(entity);
        DAO.update(subscriber);
    }
      
    @Override
    protected Map<Integer, PhoneNumber> getDataSource() {
        return dataSource;
    }

    @Override
    protected Integer getAndIncreaseCounter() {
        return counter++;
    }

    @Override
    public PhoneNumber readByNumber(String number) {
        for (PhoneNumber phoneNumber:dataSource.values()){
            if(phoneNumber.getNumber().equals(number)){
                return phoneNumber;
            }
        }
        return null;
    }

    @Override
    public List<PhoneNumber> findBySubscriber(String name) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}